<template>
	<view class="content" v-if="isLogin">
		<image class="active-banner" src="/static/image/home/banner@2x.png"></image>
		<view class="set-wrap">
			<view class="item-box item-box-short" id='tuningView' @click="openTuningPickerView()">
				<image class="item-icon" src="/static/image/home/icon2.png"></image>
				<view class="item-value">
					{{deviceInfo.tuning}}
				</view>
				<view class="text">
					选调/变调
				</view>
			</view>
			<view class="item-box item-box-short item-box-active" id='speedView' @click="speedTuningPickerView()">
				<image class="item-icon" src="/static/image/home/icon4.png"></image>
				<view class="item-value">
					{{deviceInfo.speed}}
				</view>
				<view class="text">
					弹奏速度
				</view>
			</view>
			<view class="item-box item-box-long" @click="jumpToSetting">
				<image class="item-icon" src="/static/image/home/icon1.png"></image>
				<image class="item-img" src="/static/image/home/long-icon.png"></image>
				<view class="text">
					乐器/节奏型设置
				</view>
			</view>
			<view class="item-box item-box-long" @click="jumpToMachineSetting">
				<image class="item-icon" src="/static/image/home/icon3.png"></image>
				<image class="item-img" src="/static/image/home/long-icon.png"></image>
				<view class="text">
					鼓机设置
				</view>
			</view>
		</view>
		<view class="page-mask" v-if="tuningPickerMaskVisible" @click="closeTuningPickerView()">
			<view class="item-box" :style="tuningPickerViewStyle" @click.stop>
				<image class="item-icon" src="/static/image/home/icon2.png"></image>
				<view class="active"></view>
				<picker-view indicator-class="my-indicator" :indicator-style="indicatorStyle"
					:value="[cacheTuningValueIdx]" @change='bindTuningChange' class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in tuningList" :key="item">{{item}}</view>
					</picker-view-column>
				</picker-view>

				<view class="text" @click="confirmTuning()">
					确定
				</view>
			</view>
		</view>

		<view class="page-mask" v-if="speedPickerMaskVisible" @click="closeSpeedPickerView()">
			<view class="item-box" :style="speedPickerViewStyle" @click.stop>
				<image class="item-icon" src="/static/image/home/icon4.png"></image>
				<view class="active"></view>
				<picker-view indicator-class="my-indicator" :indicator-style="indicatorStyle"
					:value="[cacheSpeedValueIdx]" @change='bindSpeedChange' class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in speedList" :key="item">{{item}}</view>
					</picker-view-column>
				</picker-view>
				<view class="text" @click="confirmSpeed()">
					确定
				</view>
			</view>
		</view>
	</view>
</template>
<script lang="ts" setup>
	import { ref, shallowRef } from 'vue';
	import { onShow, onHide } from '@dcloudio/uni-app'
	import Bluetooth from '@/utils/Bluetooth';
	import { decimalToHex } from '@/utils/tools';


	const deviceInfo = ref({
		tuning: '#C',
		speed: 40,
	})
	const indicatorStyle = `height: 48rpx;content: none!important;`

	/* ------------------------------------------------------------------------------------- 更新 选调/变调 ------------------------------------------------------------------------------------- */
	const tuningList = shallowRef(['C', '#C', 'D', '#D', 'E', 'F', '#F', 'G', '#G', 'A', '#A', 'B']);
	const cacheTuningValueIdx = ref(0);
	const tuningPickerMaskVisible = ref(false);
	const tuningPickerViewStyle = ref({ top: '0px', left: '0px' });
	const openTuningPickerView = () => {
		const query = uni.createSelectorQuery();
		const finIdx = tuningList.value.findIndex(item => item === deviceInfo.value.tuning);
		cacheTuningValueIdx.value = finIdx < 0 ? 0 : finIdx;
		query.select("#tuningView").boundingClientRect((data) => {
			tuningPickerViewStyle.value = {
				top: data.top + 'px',
				left: data.left + 'px'
			}
			tuningPickerMaskVisible.value = true;
			tabBarMaskView.show();
		}).exec();

	}

	const bindTuningChange = (e) => {
		cacheTuningValueIdx.value = e.detail.value[0]
	}

	const confirmTuning = () => {
		closeTuningPickerView();
	}

	const closeTuningPickerView = () => {
		tabBarMaskView.hide();
		cacheTuningValueIdx.value = 0;
		tuningPickerMaskVisible.value = false;
	}

	const updateTuning = async (tuningValue : number) => {
		const bluetoothInstance = await Bluetooth.getInstance();
		const hexString = decimalToHex(tuningValue)
		bluetoothInstance.writeBLECharacteristicValue('010001' + hexString);
	}

	/* ------------------------------------------------------------------------------------- 更新 弹奏速度 ------------------------------------------------------------------------------------- */

	const speedList = shallowRef([...Array(201)].map((_, i) => i + 40));
	const cacheSpeedValueIdx = ref(0);
	const speedPickerMaskVisible = ref(false);
	const speedPickerViewStyle = ref({ top: '0px', left: '0px' });
	const speedTuningPickerView = () => {
		const query = uni.createSelectorQuery();
		const finIdx = speedList.value.findIndex(item => item === deviceInfo.value.speed);
		cacheSpeedValueIdx.value = finIdx < 0 ? 0 : finIdx;
		console.log(finIdx)
		query.select("#speedView").boundingClientRect((data) => {
			speedPickerViewStyle.value = {
				top: data.top + 'px',
				left: data.left + 'px'
			}
			speedPickerMaskVisible.value = true;
			tabBarMaskView.show();
		}).exec();
	}
	const bindSpeedChange = (e) => {
		cacheSpeedValueIdx.value = e.detail.value[0]
	}
	const confirmSpeed = () => {
		updateSpeed(speedList.value[cacheSpeedValueIdx.value])
		closeSpeedPickerView();
	}

	const closeSpeedPickerView = () => {
		tabBarMaskView.hide();
		cacheSpeedValueIdx.value = 0;
		speedPickerMaskVisible.value = false;
	}

	const updateSpeed = async (speedValue : number) => {
		const bluetoothInstance = await Bluetooth.getInstance();
		const hexString = decimalToHex(speedValue)
		bluetoothInstance.writeBLECharacteristicValue('010001' + hexString);
	}

	const system = uni.getSystemInfoSync();
	const tabBarHeight = system.screenHeight - system.windowHeight;
	var tabBarMaskView = new plus.nativeObj.View("maskView", { // 给遮罩层一个唯一标识
		position: "absolute", // 设置为绝对定位
		// top: '0', // 调整顶部距离，如果要遮挡整个页面包括tabbar，可能需要计算屏幕高度减去tabbar的高度
		bottom: '0',
		left: '0',
		width: "100%", // 宽度充满屏幕
		height: `${tabBarHeight}px`, // 高度充满屏幕，如果只想遮挡tabbar，可以调整此值为tabbar的高度
		backgroundColor: "rgba(34, 34, 34, 0.69)", // 透明遮罩背景
	});


	const isLogin = ref(true);
	// 检查登录状态并跳转到相应的页面

	onShow(async () => {
		checkLoginAndRedirect();
		// 首页比较特殊，可能页面已经加载但是app.vue内的蓝牙初始化连接等还未执行完成，所以需要在这里进行一个轮询
		const bluetoothInstance = await Bluetooth.getInstance();
		const instanceInfo = bluetoothInstance.getBluetoothInstanceInfo();
		if (!instanceInfo.characteristicsWrite) {
			console.log('没准备好不能发送')
			const waitTimer = setInterval(() => {
				if (instanceInfo.characteristicsWrite) {
					bluetoothInstance.writeBLECharacteristicValue('07');
					clearInterval(waitTimer)
				}
			}, 500)
		} else {
			wx.showLoading({
				title: '加载中'
			})
			await bluetoothInstance.writeBLECharacteristicValue('07');
			wx.hideLoading()
		}
	})


	const jumpToSetting = () => {
		uni.navigateTo({
			url: '/pages/pace-config/index'
		})
	}

	const jumpToMachineSetting = () => {
		uni.navigateTo({
			url: "/pages/drum-machine-config/index"
		})
	}

	const checkLoginAndRedirect = async () => {
		const token = uni.getStorageSync('token')
		if (!token) {
			isLogin.value = false;
			uni.hideTabBar()
			uni.navigateTo({
				url: '/pages/login/index'
			});
		} else {
			uni.showTabBar()
			isLogin.value = true;
		}
	}
</script>
<style lang="scss">
	.content {
		padding: 0 32rpx;
		padding-top: 120rpx;
		padding-bottom: 40rpx;

		.active-banner {
			width: 686rpx;
			height: 226rpx;
			margin: 0 auto;
		}

		.set-wrap {
			display: flex;
			justify-content: space-between;
			flex-wrap: wrap;
			flex-direction: row;

			.item-box {

				.item-icon {
					width: 44rpx;
					height: 44rpx;
					position: relative;
				}

				.text {
					position: relative;
					right: 0;
					bottom: 0;
					text-align: right;
					font-weight: 400;
					font-size: 28rpx;
					color: #FFFFFF;
					line-height: 40rpx;
				}
			}

			.item-box-short {
				width: 330rpx;
				height: 240rpx;
				background: #242424;
				border-radius: 16rpx;
				padding: 18rpx 24rpx 24rpx 18rpx;
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				margin-top: 40rpx;

				.item-value {
					text-align: center;
				}
			}

			.item-box-long {
				width: 100%;
				height: 240rpx;
				border-radius: 16rpx;
				padding: 22rpx 24rpx 24rpx 22rpx;
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				background: #242424;
				margin-top: 40rpx;

				.item-img {
					width: 314rpx;
					height: 72rpx;
					margin-top: 34rpx;
					margin-bottom: 4rpx;
				}
			}
		}

		.page-mask {
			background-color: rgba(34, 34, 34, 0.69);
			z-index: 999999;
			position: fixed;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;
			display: flex;
			justify-content: center;
			align-items: center;

			.item-box {
				position: absolute;
				width: 330rpx;
				height: 240rpx;
				background: #30B6FF;
				border-radius: 16rpx;
				padding: 18rpx 24rpx 24rpx 18rpx;
				display: flex;
				box-sizing: border-box;
				flex-direction: column;
				justify-content: space-between;

				&.speed {
					width: 332rpx;
					background: #8436FF;

					.item-icon {
						width: 40rpx;
						height: 42rpx;
					}

					.text {
						color: #222;
					}
				}

				.item-icon {
					width: 44rpx;
					height: 44rpx;
					position: absolute;
					top: 18rpx;
					left: 18rpx;
				}

				.text {
					width: 92rpx;
					height: 42rpx;
					background: #FFFFFF;
					border-radius: 21rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #30B6FF;
					line-height: 40rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					position: absolute;
					bottom: 24rpx;
					right: 24rpx;
				}
			}

			.picker-view {
				width: 100%;
				height: 100%;
				text-align: center;

				:deep .uni-picker-view-mask {
					background-image: none !important;
				}

				:deep .my-indicator::after {
					border-bottom: none !important;
				}

				:deep .my-indicator::before {
					border-top: none !important;
				}

				.item {
					width: 108rpx;
					height: 48rpx;
					// padding: 0 32rpx;
					background: transparent;
					border-radius: 24rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-weight: 400;
					font-size: 32rpx;
					color: #D4D4D4;
					line-height: 36rpx;
					margin: 0 auto;
				}
			}

			.active {
				width: 108rpx;
				height: 48rpx;
				position: absolute;
				left: 0;
				right: 0;
				margin: auto;
				top: 0;
				bottom: 0;
				border-radius: 24rpx;
				background: #151515;
				color: #F7F7F7;
			}
		}
	}
</style>
